package com.lkd.http.controller;

import com.github.wxpay.plus.WXConfig;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.service.ESOrderService;
import com.lkd.service.OrderService;
import com.lkd.vo.OrderVO;
import com.lkd.vo.Pager;
import com.lkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    /*
    * 创建订单
    * */
    @PostMapping("/weixinPay")
    public Map<String,String> weixinPay(@RequestBody PayVO payVO){
        return orderService.weixinPay(payVO);
    }



    @Autowired
    private WxPayTemplate wxPayTemplate;

    /*
    * 微信支付回调接口
    * */
   @RequestMapping("/payNotify")
   public void payNotify(HttpServletRequest request,HttpServletResponse response) throws Exception {
       //1.接收为你心回调参数
       Map<String, String> resultMap = wxPayTemplate.validPay(request.getInputStream());
       //2. 判断交易是否成功
       if(resultMap.get("code").equals("FAIL")){
           return;
       }
       //3.调用service订单状态修改
       orderService.payNotify(resultMap);
       //4.返回业务处理结果
       response.setContentType("text/xml");// 指定返回数据的类型
       response.getWriter().write(WXConfig.RESULT);


   }



    @Autowired
    private ESOrderService esOrderService;

    /*
     * 订单查询
     * */
    @GetMapping("/search")
    public Pager<OrderVO> search(
            @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageIndex,
            @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize,
            String orderNo,
            String openId,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @DateTimeFormat(pattern = "yyy-MM-dd") LocalDate endDate) throws Exception {
        return esOrderService.search(pageIndex,pageSize,orderNo,openId,startDate,endDate);
    }




}